import os
import uuid
from loguru import logger
from service.cmd import bdf_transformer
from service.cmd import op2_transformer
from Connector.client import res_success
from service.DataCenter import db
from service.func.read_vtu import read_vtu
from service.utils.download_file import (
    create_folder_if_not_exists,
    unzip_file,
    download_file,
)
from CloudEngine.utils.memTable import memTbl
from service.utils.get_file_local_path import get_file_local_path
from service.func.read_cgns import read_cgns


def write_file(file_name, content):
    """
    将指定内容写入指定文件
    :param file_name: 文件名
    :param content: 文件内容
    """
    with open(file_name, "w") as f:
        f.write(content)


class CmdFileRead:
    name = "file_read"
    id = uuid.uuid4()

    def __init__(self, service, Params, Tag, Type):
        self.service = service
        self.params = Params
        self.tag = Tag
        self.type = Type

    async def execute(self):
        if self.params.get("FileType") == "bdf":
            ExtendOptions = self.params.get("ExtendOptions")
            OnlyRenderInfo = True
            if self.params.get("OnlyRenderInfo") is not None:
                OnlyRenderInfo = self.params.get("OnlyRenderInfo")
            tmp = str(uuid.uuid4()) + "tmpbdf.json"
            bdf_parser = None
            # zip压缩的文件包
            if ExtendOptions and ExtendOptions.get("ZipPath"):
                entry_file_path = self.params.get("path")
                zip_file_path = ExtendOptions.get("ZipPath")
                unzip_dir = "./tmp/" + str(uuid.uuid4()) + "zip/"
                create_folder_if_not_exists(unzip_dir)

                # 下载到本地
                # 如果是http文件地址
                if zip_file_path.find("http") != -1:
                    download_file(zip_file_path, unzip_dir + "origin.zip")
                else:
                    db.S3.download_file(zip_file_path, unzip_dir + "origin.zip")
                unzip_file(unzip_dir + "origin.zip", unzip_dir)

                try:
                    bdf_parser = bdf_transformer.BdfTransformer(
                        unzip_dir + entry_file_path, False, True, True, OnlyRenderInfo
                    )
                except RuntimeError:
                    print("更改参数尝试1")
                    try:
                        bdf_parser = bdf_transformer.BdfTransformer(
                            unzip_dir + entry_file_path,
                            False,
                            False,
                            True,
                            OnlyRenderInfo,
                        )
                    except RuntimeError:
                        print("更改参数尝试2")
                        try:
                            bdf_parser = bdf_transformer.BdfTransformer(
                                unzip_dir + entry_file_path,
                                False,
                                False,
                                False,
                                OnlyRenderInfo,
                            )
                        except RuntimeError:
                            logger.warning("更改参数尝试3")
                            bdf_parser = bdf_transformer.BdfTransformer(
                                unzip_dir + entry_file_path,
                                True,
                                True,
                                True,
                                OnlyRenderInfo,
                            )

            else:
                path: str = self.params.get("path")
                entry_file = str(uuid.uuid4()) + ".bdf"
                # http文件地址
                if path.find("http") != -1:
                    download_file(path, "./tmp/" + entry_file)
                else:
                    db.S3.download_file(path, "./tmp/" + entry_file)
                try:
                    bdf_parser = bdf_transformer.BdfTransformer(
                        "./tmp/" + entry_file,
                        False,
                        False,
                        False,
                        only_render_info=OnlyRenderInfo,
                    )
                except RuntimeError:
                    try:
                        bdf_parser = bdf_transformer.BdfTransformer(
                            "./tmp/" + entry_file,
                            False,
                            False,
                            True,
                            only_render_info=OnlyRenderInfo,
                        )
                    except RuntimeError:
                        bdf_parser = bdf_transformer.BdfTransformer(
                            "./tmp/" + entry_file,
                            False,
                            True,
                            True,
                            only_render_info=OnlyRenderInfo,
                        )
            json_data = bdf_parser.to_json()
            # ➡️ 处理InMemory参数
            if ExtendOptions and ExtendOptions.get("InMemory"):
                memTbl.set("bdf", json_data)

            path = db.S3.upload_json("/bdf/" + tmp, json_data)

            await res_success(
                self.tag,
                self.type,
                {
                    "DataPath": path,
                    "DataEngine": "FileServer",
                },
            )

        # TODO 还没有完成
        if self.params.get("FileType") == "op2":
            op2_parser = op2_transformer.Op2Transformer(
                "C:/Users/Chris/Downloads/stp_demo/panel.op2"
            )
            tmp = str(uuid.uuid4()) + "tmpop2.json"
            write_file(
                "D:/CombineDevelopEnv/server/NodeService/public/temp/" + tmp,
                op2_parser.to_json(),
            )
            await res_success(self.tag, self.type, "http://localhost:3000/temp/" + tmp)

        if self.params.get("FileType") == "vtu":
            path = self.params.get("path")
            path = get_file_local_path(path, "vtu")
            read_vtu(path)
            await res_success(self.tag, self.type, "ok")

        # cgns TODO 还没有完成
        if self.params.get("FileType") == "cgns":
            path: str = self.params.get("path")
            entry_file = str(uuid.uuid4()) + ".cgns"
            # http文件地址
            if path.find("http") != -1:
                download_file(path, "./tmp/" + entry_file)
            else:
                db.S3.download_file(path, "./tmp/" + entry_file)
